package com.itboye.ihomebank.activity.qianyue;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.mobileim.lib.model.message.IFileMessage;
import com.itboye.ihomebank.R;
import com.itboye.ihomebank.base.BaseOtherActivity;
import com.itboye.ihomebank.bean.ApplyStageBean;
import com.itboye.ihomebank.bean.QianYueDetailBean;
import com.itboye.ihomebank.bean.ResultEntity;
import com.itboye.ihomebank.constants.NetPublicConstant;
import com.itboye.ihomebank.constants.SPContants;
import com.itboye.ihomebank.presenter.UserPresenter;
import com.itboye.ihomebank.util.ByAlert;
import com.itboye.ihomebank.util.DoubleUtil;
import com.itboye.ihomebank.util.SPUtils;
import com.itboye.ihomebank.util.TimesUtils;
import com.itboye.ihomebank.web.StageApply;
import com.itboye.ihomebank.web.WebActivity;
import com.itboye.ihomebank.zjtlcb.lnd.livenessdetector.activity.MainLiveActivity;

import java.util.Observable;
import java.util.Observer;

public class OrderDetailActivity extends BaseOtherActivity implements Observer {
    View v_statusbar;
    String contractNo;
    ImageView close_icon;
    TextView add_shap_title_tv;
    Button bankFq, chakan;
    UserPresenter userPresenter;
    private String uid;
    private QianYueDetailBean detailBean;
    LinearLayout dingjin_detail;
    TextView payDepositTv;
    TextView txt_hetongno, txt_finishtime, txt_hetongstatus, txt_chuzurenname,
            txt_chuzurenmobile, txt_chengzurenname, txt_chengzurenmobile;
    private String password;
    public static OrderDetailActivity context;
    public static int TAILONGREQUEST=111;
    public static String url;//申请分期 url

    public static OrderDetailActivity getContext() {
        return context;
    }
    String contract_type;
    String stage_apply;

    String userType;//房东lesser
    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        Intent intent = null;

        switch (v.getId()) {
            case R.id.close_icon:
                finish();
                break;
            case R.id.txt_chengzurenmobile:
                if (detailBean==null){
                    ByAlert.alert("暂时不能拨打电话");
                    return;
                }
                intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:"
                        + detailBean.getRenterMobile()));
                startActivity(intent);
                break;

            case R.id.bankFq:
                bankFq.setEnabled(false);
                showProgressDialog("申请中请稍后...",true);
                userPresenter.applyStage(uid,contractNo);

//                Intent intent1 = new Intent(this, StageApply.class);
//                intent1.putExtra("url",url);
//                intent1.putExtra("title","泰隆分期申请");
//                startActivity(intent1);
                break;
            case R.id.chakan:
                System.out.println("hetong ------>>>" + NetPublicConstant.HETONG_URL + "?uid=" + uid
                        + "&psw=" + password + "&contract_no=" + contractNo
                        + "&pc=1");
                intent = new Intent(this, WebActivity.class);
                intent.putExtra("url", NetPublicConstant.HETONG_URL + "?uid=" + uid
                        + "&psw=" + password + "&contract_no=" + contractNo
                        + "&pc=1");
                intent.putExtra("title", "查看合同");
                startActivity(intent);
                break;
            default:
                break;
        }
    }

    @Override
    protected int layout_id() {
        // TODO Auto-generated method stub
        return R.layout.activity_orderdetail;
    }

    @Override
    protected void onInitController() {
        // TODO Auto-generated method stub
    }

    @Override
    protected void onResume() {
        super.onResume();
        userPresenter.qianyueDetail(uid, contractNo);
    }

    @Override
    protected void onInit() {
        // TODO Auto-generated method stub
        setStatusBarHeight(v_statusbar);
        showProgressDialog("获取数据中,请稍后", true);
        context = this;
        stage_apply= getIntent().getStringExtra("can_bank_stage_apply");
        contract_type = getIntent().getStringExtra("contract_type");
        contractNo = getIntent().getStringExtra("contractNo");

        userType = getIntent().getStringExtra("user_type");
//        bank = getIntent().getIntExtra("bank",-1);
        System.out.println(contractNo + "签约详情");
        add_shap_title_tv.setText("签约详情");



        userPresenter = new UserPresenter(this);
        uid = SPUtils.get(this, null, SPContants.USER_ID, "") + "";
        password = SPUtils.get(this, null, SPContants.PASSWORD, "") + "";


    }

    @Override
    protected void onReadIntent(Bundle bundle) {
        // TODO Auto-generated method stub

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==TAILONGREQUEST&&resultCode==TAILONGREQUEST){


        }
    }

    @Override
    public void update(Observable observable, Object data) {
        // TODO Auto-generated method stub
        ResultEntity entity = handlerError(data);
        if (entity != null) {
            if (entity.getEventType() == UserPresenter.qianyuedetail_success) {
                detailBean = (QianYueDetailBean) entity.getData();
                setInfo(detailBean);
            } else if (entity.getEventType() == UserPresenter.qianyuedetail_fail) {
                ByAlert.alert(entity.getData());
            }else if (entity.getEventType() == UserPresenter.applyStage_success){

                ApplyStageBean data1 = (ApplyStageBean) entity.getData();

                url=data1.getQrc_url();

//                if(url!=null||!url.equals("")){
//                    Uri uri = Uri.parse(url);
//                    Intent intent4 = new Intent(Intent.ACTION_VIEW, uri);
//                    startActivity(intent4);
//                }
                Log.d("========",url);
                if (url!=null){
                    Intent intent = new Intent(this, MainLiveActivity.class);
                    String[] split = url.split("bussSeqNo=");

                    intent.putExtra("bussSeqNo=",split[1]);
                    startActivity(intent);

                }
                 bankFq.setEnabled(true);
//                ByAlert.alert(data1.getQrc_url());
            }else if (entity.getEventType() == UserPresenter.applyStage_fail){
                bankFq.setEnabled(true);
                ByAlert.alert(entity.getMsg());
            }
        }
        try {
            closeProgressDialog();
        } catch (Exception e) {
            // TODO: handle exception
        }
    }

    @SuppressLint("NewApi")
    private void setInfo(QianYueDetailBean detailBean) {
        // TODO Auto-generated method stub
        final QianYueDetailBean bean = detailBean;
        if (bean != null) {
            if (!bean.getUser_type().equals("lesser")){
                if (bean.getContract_type().equals("4")){//银行分期
                    if (bean.getCan_bank_stage_apply().equals("1")){ //可以申请
                        bankFq.setVisibility(View.VISIBLE);
                    }else {
                        bankFq.setVisibility(View.GONE);
                    }
                }

            }
            txt_hetongno.setText(bean.getContractNo());
            txt_finishtime.setText(TimesUtils.timeStamp2Date(Long.parseLong(bean.getCompleteTime())));
            txt_hetongstatus.setText(bean.getContractStatus());
            txt_chuzurenmobile.setText(bean.getOwnerMobile());
            txt_chengzurenmobile.setText(bean.getRenterMobile());
            txt_chuzurenname.setText(bean.getOwnerName());
            txt_chengzurenname.setText(bean.getRenterName());
            if (bean.getContractStatus().equals("1")) {
                txt_hetongstatus.setText("正常");
                if (bean.getTerminate_status().equals("0")) {
                    txt_hetongstatus.setText("正常");
                } else {
                    txt_hetongstatus.setText("终止");
                    txt_hetongstatus.setTextColor(this.getResources().getColor(R.color.orange_red02));
                }

            } else {
                txt_hetongstatus.setText("异常");
            }
            if (bean.getPayInfo() != null) {
                dingjin_detail.removeAllViews();
                for (int i = 0; i < bean.getPayInfo().size(); i++) {

                    View view = LayoutInflater.from(this).inflate(
                            R.layout.item_hetong_zujin, null);
                    TextView txt01 = (TextView) view.findViewById(R.id.txt01);
                    TextView textView = (TextView) view.findViewById(R.id.txt);
                    TextView txt_device = (TextView) view.findViewById(R.id.txt_device);
                    final TextView editText = (TextView) view.findViewById(R.id.edit);

                    txt01.setText(i + 1 + "");
                    textView.setText(DoubleUtil.doubleTransform(bean.getPayInfo().get(i).getItemPrice()));
                    txt_device.setText(bean.getPayInfo().get(i).getItemDate());
                    editText.setTag(DoubleUtil.doubleTransform(bean.getPayInfo().get(i).getItemPrice()));
                    editText.setTag(R.id.tag, bean.getPayInfo().get(i).getItemId());
                    editText.setTag(R.id.tagNames, bean.getContractNo());
                    if (bean.getContract_type().equals("4")){
                       editText.setEnabled(false);
                       editText.setBackgroundResource(R.drawable.shape_gry01);
                    }else {
                        editText.setEnabled(true);
                    }
                    editText.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (editText.getText().toString().equals("去支付")) {
                                Intent intent = new Intent(OrderDetailActivity.this,PayActivity.class);
                                intent.putExtra("money", v.getTag().toString());
                                intent.putExtra("contract_no",v.getTag(R.id.tagNames).toString());
                                intent.putExtra("itemid", v.getTag(R.id.tag).toString());
                                intent.putExtra("pay_code_type", "house_rent");
                                intent.putExtra("time",Long.parseLong(bean.getCompleteTime())*1000);
                                startActivity(intent);
                            }
                        }
                    });
                    if (uid.equals(bean.getOwnerUid())) {// 如果是房东身份
                        editText.setTextColor(getResources().getColor(R.color.gray_two));
                        editText.setText(bean.getPayInfo().get(i)
                                .getItemPayStatus().equals("0") ? "等待房客支付": "支付完成");
                    } else {// 如果是租客身份
                        if (bean.getPayInfo().get(i).getItemPayStatus().equals("0")) {//未支付
                            editText.setBackgroundResource(R.drawable.shape_green01);
                            editText.setTextColor(getResources().getColor(R.color.white));
                            editText.setGravity(Gravity.CENTER);
                            if (i > 0) {
                                String status = bean.getPayInfo().get(i - 1).getItemPayStatus();
                                if (status.equals("0")) {//当前一个还没有去支付的时候，这个不能先支付
                                    editText.setBackgroundResource(R.drawable.shape_gry01);
                                    editText.setTextColor(getResources().getColor(R.color.white));
                                    editText.setClickable(false);
                                    editText.setGravity(Gravity.CENTER);
                                }
                            }
                        } else {
                            editText.setBackgroundResource(R.drawable.shape_gry01);
                            editText.setTextColor(getResources().getColor(R.color.white));
                            editText.setGravity(Gravity.CENTER);
                            editText.setClickable(false);
                        }

                        if (bean.getTerminate_status().equals("0")) {//0正常 1:终止


                            if (bean.getContract_type().equals("4")){
                                editText.setText(bean.getPayInfo().get(i)
                                        .getItemPayStatus().equals("0") ? "未支付"
                                        : "已支付");
                            }else {
                                editText.setText(bean.getPayInfo().get(i)
                                        .getItemPayStatus().equals("0") ? "去支付"
                                        : "已支付");
                            }
                        } else {
                            editText.setVisibility(View.GONE);
                        }
                    }
                    dingjin_detail.addView(view);
                }
            }
            //分期支付情况
        }
    }



}
